package com.example.test_demo.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: test
 * @description: ss
 * @author: yanghua
 * @create: 2021-08-13 11:27
 **/

public class ServiceTest {
    /**
     * 使用线程池
     */
    public void insertDataExecutors(){
        int dataSize = 10000;//数据的条数
        //每条线程执行500个数据,需要多少个线程?
        int threadNumber = dataSize/500==0?dataSize/500:dataSize/500+1;//开启的线程数
        CountDownLatch countDownLatch = new CountDownLatch(dataSize);
        ExecutorService executor = Executors.newFixedThreadPool(threadNumber);
        //出现异常返回
        final int[] flag = {0};
        try{
            for(int i=0;i<threadNumber;i++) {
                int index = i;
                //500一组切割list集合,调用函数List.subList(i*500, (i+1)*500)
                executor.execute(() -> {
                    try{
                        //你的业务逻辑  inDbdataList.subList(fromIndex, toIndex)
                        System.out.println("第"+index+"开始执行");
                        //沉睡1分钟,相当于业务的执行时间,而在沉睡期间会不会开启另外一个线程执行业务?
                        Thread.sleep(60*1000);
                        System.out.println("沉睡1分钟后 第"+index+"执行完成");

                    }catch(Exception e){
                        //写入日志
                        System.out.println("第"+index+"条出错  "+e.getMessage());
                        flag[0] = 1;
                        throw new RuntimeException("第"+index+"条出错  ");
                    }finally {
                        countDownLatch.countDown();
                    }
                });
            }
            System.out.println("循环结束,但不代表业务已经彻底完成");
            countDownLatch.await();
            System.out.println("countDownLatch计数器为0了  我才执行");
        }catch(Exception e){

        }finally {
            executor.shutdown();
        }
        System.out.println("完成了.");

    }
    /**
     * 直接使用new Thread
     */
    public void insertDataNewThread(){
        try{
            int dataSize = 10000;//数据的条数
            final CountDownLatch countDownLatch = new CountDownLatch(dataSize);
            for (int i = 0; i < dataSize; i++) {
                int finalI = i;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            System.out.println("第"+ finalI +"开始执行");
                            //沉睡1分钟,相当于业务的执行时间,而在沉睡期间会不会开启另外一个线程执行业务?
                            Thread.sleep(60*1000);
                            System.out.println("沉睡1分钟后 第"+ finalI +"执行完成");
                        } catch (Exception e) {

                        }
                        countDownLatch.countDown();
                    }
                }).start();
            }
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {

            }

        }catch(Exception e){

        }
    }

}
